/*
 * $Id: ConnectivityUtil.java,v 1.6 2010/07/23 01:35:23 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.common.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.med.service.mc.MakeConnection;
import com.ge.med.service.mc.exceptions.MakeConnectionException;

/**
 * @author 212042764
 * 
 */
public class ConnectivityUtil {
	private static final String USER = "autosc";
	private static final String PLATFORM = "autosc";

	/**
	 * This method can be used to bring a system to GE domain
	 * 
	 * @param systemId
	 *            - is System ID or Secondary Service Code
	 * @param appId
	 *            - is the Application ID for Chronology purpose.
	 * @param attemptNum
	 *            - is the Connection Attempt Number for Chronology purpose.
	 * @param rfsNum
	 *            - is the Dispatch Number for Chronology purpose.
	 * @return - boolean indicating whether make connection was successful or
	 *         not
	 * @throws MakeConnectionException
	 *             - Failed to connect
	 */
	public static void makeConnection(String systemId, String appId,
			int attemptNum, String rfsNum) throws MakeConnectionException {
		String methodName = "makeConnection";
		StringWriter outputBuffer = new StringWriter();
		PrintWriter connectOutput = new PrintWriter(outputBuffer, true);
		MakeConnection mc = null;

		try {
			mc = new MakeConnection(connectOutput, systemId, USER, appId,
					rfsNum, attemptNum, PLATFORM);
			// Time to see if we can connect
			if (mc.connect()) {
				ASCLogger.info(ConnectivityUtil.class, methodName,
						getMCSuccessMessage(mc, systemId, outputBuffer), true);
			} else {
				ASCLogger.info(ConnectivityUtil.class, methodName,
						getMCErrorMessage(mc, systemId, outputBuffer), true);
				throw new MakeConnectionException(getMCErrorMessage(mc,
						systemId, outputBuffer));
			}
		} catch (MakeConnectionException mcException) {
			ASCLogger.info(ConnectivityUtil.class, methodName,
					getMCErrorMessage(mc, systemId, outputBuffer), mcException, true);
			throw mcException;
		} finally {
			try {
				if (!ASCUtil.isNullOrEmptyObject(outputBuffer)) {
					outputBuffer.close();
				}
			} catch (IOException ioException) {
				// This is not an error as i don't care for output buffer
				ASCLogger.info(ConnectivityUtil.class, methodName,
						"Failed to close output buffer", ioException);
			}
			connectOutput.close();
		}
	}

	/**
	 * Get message to log if make connection is successful
	 * 
	 * @param mc
	 * @param systemId
	 * @param outputBuffer
	 * @return
	 */
	private static String getMCSuccessMessage(MakeConnection mc,
			String systemId, StringWriter outputBuffer) {
		return new StringBuffer().append(
				"Successfully established connection to ").append(systemId)
				.append(":\n").append("MakeConnection version: ").append(
						mc.getVersionString()).append("\n").append(
						outputBuffer.toString()).toString();
	}

	/**
	 * Get message to log if make connection fails
	 * 
	 * @param mc
	 * @param systemId
	 * @param outputBuffer
	 * @return
	 */
	private static String getMCErrorMessage(MakeConnection mc, String systemId,
			StringWriter outputBuffer) {
		StringBuffer responseBuffer = new StringBuffer().append(
				"Connection to ").append(systemId).append(
				" could not be established.");
		if (!ASCUtil.isNullOrEmptyObject(mc)) {
			responseBuffer.append("MakeConnection version: ").append(
					mc.getVersionString()).append("\n").append(
					outputBuffer.toString());
		}
		return responseBuffer.toString();
	}

}
